package com.springboot.killingsystem.rabbitmq;

import com.springboot.killingsystem.domain.SecondKillingOrder;
import com.springboot.killingsystem.domain.SecondKillingUser;
import com.springboot.killingsystem.redis.RedisService;
import com.springboot.killingsystem.service.GoodsService;
import com.springboot.killingsystem.service.OrderService;
import com.springboot.killingsystem.service.SecondKillingService;
import com.springboot.killingsystem.util.Constant;
import com.springboot.killingsystem.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MQReceiver {

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    SecondKillingService secondKillingService;

    @RabbitListener(queues = Constant.SECOND_KILLING_QUEUE)
    public void receive(String message) {
        log.info("receive message:"+message);
        SecondKillingMessage msg = RedisService.stringToBean(message, SecondKillingMessage.class);
        SecondKillingUser user = msg.getUser();
        long goodsId = msg.getGoodsId();
        // 判断库存
        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        int stock = goods.getStockCount();
        if (stock <= 0) {
            return;
        }
        // 判断是否已经秒杀到了多个商品
        SecondKillingOrder order = orderService.getSecondsKillingOrderByGoodsId(user.getId(), goodsId);
        if (order != null) {
            return;
        }

        // 减库存 下订单 写入秒杀订单
        secondKillingService.secondKilling(user, goods);
    }
}
